package cn.jroid.demo.adapter;


import java.util.List;

import android.app.Activity;
import android.graphics.drawable.Drawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import cn.jroid.demo.R;
import cn.jroid.demo.cache.ViewCache;
import cn.jroid.demo.entity.Image;
import cn.jroid.demo.util.AsyncImageLoader;
import cn.jroid.demo.util.AsyncImageLoader.ImageCallback;
import cn.jroid.demo.util.AsyncImageLoader2;

public class ImageListAdapter extends ArrayAdapter<Image> {

	    private ListView listView;
	    private AsyncImageLoader2 asyncImageLoader;

	    public ImageListAdapter(Activity activity, List<Image> imageAndTexts, ListView listView) {
	        super(activity, 0, imageAndTexts);
	        this.listView = listView;
	        asyncImageLoader = new AsyncImageLoader2();
	    }

	    public View getView(int position, View convertView, ViewGroup parent) {
	        Activity activity = (Activity) getContext();
	        
	        // Inflate the views from XML
	        View rowView = convertView;
	        ViewCache viewCache;
	        if (rowView == null) {
	            LayoutInflater inflater = activity.getLayoutInflater();
	            rowView = inflater.inflate(R.layout.image_list_item, null);
	            viewCache = new ViewCache(rowView);
	            rowView.setTag(viewCache);
	        } else {
	            viewCache = (ViewCache) rowView.getTag();
	        }
	        Image image = getItem(position);
	        // Load the image and set it on the ImageView
	        String imageUrl = image.getImageUrl();
	        final ImageView imageView = viewCache.getImageView();
	        imageView.setTag(imageUrl);
	        
	        //final ImageView imgView = (ImageView) rowView.findViewById(R.id.image);
	        
	        Drawable cacheImage = asyncImageLoader.loadDrawable(imageUrl,
					new AsyncImageLoader2.ImageCallback() {
						// 请参见实现：如果第一次加载url时下面方法会执行
						public void imageLoaded(Drawable imageDrawable) {
							imageView.setImageDrawable(imageDrawable);
						}
			});
			if (cacheImage != null) {
				((ImageView) rowView.findViewById(R.id.image)).setImageDrawable(cacheImage);
			}

			// Set the text on the TextView
	        TextView textView = viewCache.getImageNameTextView();
	        textView.setText(image.getImageName());

	        return rowView;
	    }

}
